<template>
    <div class="patrol-line" v-loading="isLoading">
        <div class="patrol-line-item" v-if="lineList.length>0 && is_superuser || permission_map['23a']">
            <div class="patrol-line-add" @click="addPatrolLineBtn">
                <i class="el-icon-plus"></i><span>路线</span>
            </div>
        </div>
        <div class="project-epmty-main" v-if="lineList && lineList.length <= 0">
            <img src="../../../assets/empty_icon.png"/>
            <div class="create-area-tip">暂无巡更路线</div>
            <div @click="addPatrolLineBtn" v-if="is_superuser || permission_map['23a']" class="create-area-text">创建路线</div>
        </div>
        <div class="patrol-line-item" v-for="(item, $index) in lineList">
            <div class="item-con">
                <div class="line-info">
                    <div class="item-line-name"><div><span>线路名称：</span>{{item.name}}</div><div><span>负责人：</span>{{item.user_name}}</div></div>
                    <div class="item-line">
                        <span v-for="(line, $lineIndex) in item.point_list"><span class="line-text">{{line}}</span><i v-if="$lineIndex != item.point_list.length-1">→</i></span>
                    </div>
                    <div class="item-time-text">巡更时间：</div>
                    <div class="item-time-list">
                        <span v-for="t in item.time_list">{{t}}</span>
                    </div>
                </div>
                <div class="operation-btns" v-if="is_superuser || permission_map['23a']"><span @click="editLine(item, $index)">编辑</span><span @click="delLine(item, $index)">删除</span></div>
            </div>
        </div>
        <el-dialog :title="isEdit?'修改路线':'新增路线'" :visible.sync="dialogArea" width="730px" v-loading="formIsLoading">
            <el-form ref="patrolForm" :rules="rules" class="patrol-form" :model="patrolForm" label-width="110px" id="patrolForm">
                <el-form-item label="线路名称：" prop="address">
                    <el-input v-model="patrolForm.address" placeholder="请输入线路名称"></el-input>
                </el-form-item>
                <el-form-item label="负责人：" prop="user">
                    <el-select v-model="patrolForm.user" placeholder="请选择巡更人员">
                        <el-option v-for="(v, i) of staffList" :key="i" :label="v.name" :value="v.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="巡更点：" prop="projects">
                    <div class="form-divs">
                        <div class="form-div" v-for="(item, index) in patrolForm.projects" :key="index">
                            <el-select v-model="patrolForm.projects[index]" @focus="focusProjects" placeholder="请输入巡更点">
                                <el-option v-for="(v, i) of projectList" :key="i" :label="v.point_name" :value="v.point_name" :disabled="v.disabled"></el-option>
                            </el-select>
                            <i v-if="patrolForm.projects.length === index+1" class="project-icon el-icon-circle-plus-outline" @click.prevent="addPatrolProject"></i
                            ><i v-if="index!==0" class="project-icon el-icon-delete" @click.prevent="removeProject(index)"></i>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="巡更时间：" prop="times">
                    <div class="form-divs">
                        <div class="form-div" v-for="(item, index) in patrolForm.times" :key="index">
                            <el-time-select
                                placeholder="开始时间"
                                v-model="patrolForm.times[index].startTime"
                                :picker-options="{
                                    start: '00:00',
                                    end: '23:59',
                                    step: '00:15',
                                    maxTime: patrolForm.times[index].endTime
                                }">
                            </el-time-select>
                            <span class="form-div-line">—</span>
                            <el-time-select
                                placeholder="结束时间"
                                v-model="patrolForm.times[index].endTime"
                                :picker-options="{
                                    start: '00:00',
                                    end: '23:59',
                                    step: '00:15',
                                    minTime: patrolForm.times[index].startTime
                                }">
                            </el-time-select>
                            <i v-if="patrolForm.times.length === index+1 && patrolForm.times.length<3" class="project-icon el-icon-circle-plus-outline" @click.prevent="addPatrolTimes"></i
                            ><i v-if="index!==0" class="project-icon el-icon-delete" @click.prevent="removeTimes(index)"></i>
                        </div>
                    </div>
                    <div class="form-tips">注：新增巡更时间在第二天0点生效</div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogArea = false">取消</el-button>
                <el-button type="primary" @click="patrolSubmit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        props: {
            patrolPointList: Array,
            staffList: Array
        },
        data() {
            return {
                isLoading: false,
                formIsLoading: false,
                isEdit: false,
                dialogArea: false,
                staffList: [],
                projectList: [],
                lineList: [],
                lineIndex: 0,
                patrolForm: {
                    address: '',
                    user: '',
                    projects: [''],
                    times: [{
                        startTime: '',
                        endTime: ''
                    }]
                },
                rules: {
                    address: [
                        { required: true, message: '请输入巡更点', trigger: 'blur' }
                    ],
                    user: [
                        { required: true, message: '请选择巡更负责人', trigger: 'blur' }
                    ],
                    projects: [
                        { required: true, message: '请输入巡更项目', trigger: 'blur' }
                    ],
                    times: [
                        { required: true, message: '请输入巡更时间', trigger: 'blur' }
                    ]
                },
                fielId: '',
                patrolIndex: 0,
                permission_map: {},
                is_superuser: false
            }
        },
        created() {
            if(localStorage.getItem('user_info')) {
                this.permission_map = JSON.parse(localStorage.getItem('user_info')).permission_map;
                this.is_superuser = JSON.parse(localStorage.getItem('user_info')).is_superuser;
            }
            this.projectList = this.patrolPointList;
            this.requestInfo();
        },
        methods: {
            requestInfo() {
                this.isLoading = true;
                this.$http.get(`/api/v1/patrol/route/?patrol_field=${this.$route.query.id}`)
                .then((res) => {
                    this.lineList = res.data;
                    this.lineList.forEach((v) => {
                        let func = new Function('return (' + v.point_list + ');');
                        v.point_list = func();
                        let funct = new Function('return (' + v.time_list + ');');
                        v.time_list = funct();
                    })
                    this.isLoading = false;
                })
                .catch(() => {
                    this.isLoading = false;
                })
            },
            // 添加巡更路线
            addPatrolLineBtn() {
                this.dialogArea = true;
                this.isEdit = false;
                this.$nextTick(() => {
                    var container = this.$el.querySelector("#patrolForm");
                    container.scrollTop = 0;
                    this.patrolForm = {
                        address: '',
                        user: '',
                        projects: [''],
                        times: [{
                            startTime: '',
                            endTime: ''
                        }]
                    }
                    this.$refs.patrolForm.clearValidate();
                });
            },
            // 添加巡更点
            addPatrolProject() {
                this.patrolForm.projects.push('');
            },
            // 移除巡更点
            removeProject(index) {
                this.patrolForm.projects.splice(index, 1);
            },
            // 添加巡更时间
            addPatrolTimes() {
                if(this.patrolForm.times.length >= 3) this.$message.warning('最多只能添加三个巡更时间');
                else this.patrolForm.times.push({
                    startTime: '',
                    endTime: ''
                });
            },
            // 移除巡更时间
            removeTimes(index) {
                this.patrolForm.times.splice(index, 1);
            },
            // 编辑线路
            editLine(item, index) {
                this.fielId = item.id;
                this.dialogArea = true;
                this.isEdit = true;
                this.lineIndex = index;
                let times = [];
                item.time_list.map((v) => {
                    times.push({
                        startTime: v.substring(0, 5),
                        endTime: v.substring(6)
                    })
                })
                this.patrolForm = {
                    address: JSON.parse(JSON.stringify(item.name)),
                    user: JSON.parse(JSON.stringify(item.user_name)),
                    projects: JSON.parse(JSON.stringify(item.point_list)),
                    times: JSON.parse(JSON.stringify(times))
                }
                this.$nextTick(() => {
                    var container = this.$el.querySelector("#patrolForm");
                    container.scrollTop = 0;
                    this.$refs.patrolForm.clearValidate();
                })
            },
            // 删除线路
            delLine(item, index) {
                this.$confirm('是否确认删除此路线，删除后无法恢复。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.isLoading = true;
                    this.$http.delete(`/api/v1/patrol/route/${item.id}`)
                    .then((res) => {
                        this.isLoading = false;
                        this.lineList.splice(index, 1);
                        this.$message.success('删除成功');
                        this.$emit('lineEvent', this.lineList);
                    })
                    .catch(()=>{
                        this.isLoading = false;
                    })
                }).catch(() => {});

            },
            focusProjects(e) {
                this.projectList.forEach((v, i) => {
                    this.$set(this.projectList[i], 'disabled', false);
                    for(let j = 0;j< this.patrolForm.projects.length; j++) {
                        if(v.point_name !== e.target.value) {
                            if(v.point_name === this.patrolForm.projects[j]) {
                                this.$set(this.projectList[i], 'disabled', true);
                                break;
                            }
                        }
                    }
                })
            },
            patrolSubmit() {
                let times = [];
                this.$refs['patrolForm'].validate((valid) => {
                    if (valid) {
                        let projects = this.patrolForm.projects.some((val)=>{
                            return !val;
                        })
                        if(projects) {
                            this.$message.warning('请选择巡更点');
                            return false;
                        };
                        for(let i=0; i< this.patrolForm.times.length; i++) {
                            if(!this.patrolForm.times[i]) {
                                this.$message.warning('请输入巡更时间');
                                return false;
                            }
                            times.push(this.patrolForm.times[i].startTime + '-'+this.patrolForm.times[i].endTime);
                            let start_time = new Date( '2020-01-01 '+this.patrolForm.times[i].startTime+ ':00').getTime();
                            let end_time = new Date( '2020-01-01 '+this.patrolForm.times[i].endTime+ ':00').getTime();
                            let temp = 0;
                            for(let j=0;j< this.patrolForm.times.length;j++) {
                                let time1 = new Date( '2020-01-01 '+this.patrolForm.times[j].startTime+ ':00').getTime();
                                let time2 = new Date( '2020-01-01 '+this.patrolForm.times[j].endTime+ ':00').getTime();
                                if(i!== j) {
                                    if((time1 >= start_time && time1 < end_time) || (time2 > start_time && time2 < end_time)) {
                                        this.$message.warning('巡更时间段重复，请检查后重新选择！');
                                        temp = 1;
                                        break;
                                    }
                                }
                            }
                            if(temp === 1) return false;
                        }
                        this.formIsLoading = true;
                        let params = new FormData();
                        params.append('name', this.patrolForm.address);
                        params.append('time_list', times.toString());
                        params.append('point_list', this.patrolForm.projects);
                        params.append('user_name', this.patrolForm.user);
                        params.append('patrol_field', this.$route.query.id);
                        if(this.isEdit) {
                            this.$http.put(`/api/v1/patrol/route/${this.fielId}`, params)
                            .then((res) => {
                                this.dialogArea = false;
                                this.formIsLoading = false;
                                this.$message.success('巡更路线修改成功！');
                                res.data.point_list = res.data.point_list.split(',');
                                res.data.time_list = res.data.time_list.split(',');
                                this.lineList[this.lineIndex] = res.data;
                                console.log(this.lineList[this.lineIndex])

                            })
                            .catch(() => {
                                this.formIsLoading = false;
                            })
                        }else {
                            this.$http.post('/api/v1/patrol/route/', params)
                            .then((res) => {
                                this.dialogArea = false;
                                this.formIsLoading = false;
                                this.$message.success('巡更路线添加成功！');
                                this.lineList.unshift({
                                    id: res.data.id,
                                    name: res.data.name,
                                    patrol_field: res.data.patrol_field,
                                    point_list: res.data.point_list.split(','),
                                    time_list: res.data.time_list.split(','),
                                    user_name: res.data.user_name
                                })
                                this.$emit('lineEvent', this.lineList);
                            })
                            .catch(() => {
                                this.formIsLoading = false;
                            })
                        }
                    }
                })
            }
        }
    }
</script>
<style lang="scss" scoped>
    .patrol-line {
        display: flex;
        flex-wrap: wrap;
        .project-epmty-main {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            margin: 200px 0;
            flex: 1;
            &>img {
                width: 80px;
                height: 80px;
            }
            .create-area-tip {
                margin: 12px 0;
            }
            .create-area-text {
                font-weight: bold;
                font-size: 18px;
                cursor: pointer;
                color: #409eff;
            }
        }
        .patrol-line-item {
            width: 33.33%;
            padding: 12px;
            box-sizing: border-box;
        }
        .patrol-line-add {
            width: 100%;
            border: 1px dashed #e5e5e5;
            height: 200px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            line-height: 1;
            .el-icon-plus {
                margin-right: 10px;
            }
        }
        .item-con {
            width: 100%;
            border: 1px solid #e5e5e5;
            height: 200px;
            position: relative;
            .line-info {
                padding: 12px;
                box-sizing: border-box;
                height: 160px;
                overflow: auto;
                &>div {
                    margin-top: 10px;
                }
                &>div:first-child {
                    margin: 0;
                }
                .item-line-name {
                    display: flex;
                    justify-content: space-between;
                }
                .line-text {
                    color: #409eff;
                }
                .item-time-text {

                }
                .item-time-list {
                    color: #888;
                    display: flex;
                    justify-content: space-between;
                }
            }
            .operation-btns {
                position: absolute;
                width: 100%;
                height: 40px;
                bottom: 0;
                left: 0;
                display: flex;
                align-items: center;
                border-top: 1px solid #e5e5e5;
                box-sizing: border-box;
                &>span {
                    width: 50%;
                    display: flex;
                    justify-content: center;
                    background: #f7f7f7;
                    cursor: pointer;
                    color: #FF0000;
                    height: 100%;
                    align-items: center;
                }
                &>span:first-child {
                    border-right: 1px solid #e5e5e5;
                    box-sizing: border-box;
                    color: #409eff;
                }
            }
        }
        .patrol-form {
            width: 100%;
            max-height: 500px;
            overflow: auto;
            .project-icon, .project-icon-n {
                font-size: 22px;
                margin-left: 12px;
                cursor: pointer;
            }
            .project-icon-n {
                margin-top: 9px;
            }
            ::v-deep .el-input {
                width: 280px;
            }
            .form-divs {
                .form-div {
                    display: flex;
                    align-items: center;
                    margin-top: 12px;
                    ::v-deep .el-input {
                        width: 200px;
                    }
                    .form-div-line {
                        margin: 0 10px;
                    }
                }
                &>div:first-child {
                    margin-top: 0;
                }
            }
            .form-tips {
                font-size: 12px;
                color: #88B;
                margin-top: 10px;
            }
        }
    }
</style>